import { post } from "../../../utils/request";
import CodeTreeNode from "../code/tree-node";
import utils from "../../../utils/utils";
const env = import.meta.env;

const apiCode = {
  queryCodeListing(data?: object) {
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.listing",
      data
    );
  },
  getCode(codeId: string) {
    return post(env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.get", {
      codeId: codeId,
    });
  },
  updateCode(data?: object) {
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.update",
      data
    );
  },
  deleteCode(codeId: string) {
    return post(env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.delete", {
      codeId,
    });
  },
  changeCodeVisible(codeId: string, visible: number) {
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.visible.change",
      {
        codeId,
        visible,
      }
    );
  },
  /**
   *
   * @param parentId
   * @returns
   */
  queryChildrenByParentId(parentId: string) {
    // console.log("queryCodeChildrenListing", parentId);
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.children.by.parentId",
      {
        parentId,
      }
    );
  },
  queryChildrenByParentCode(parentCode: string) {
    // console.log("queryCodeChildrenListing", parentId);
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/open/code.children.by.parent.code",
      {
        parentCode,
      }
    );
  },
  queryProvince() {
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.province.query", {}
    );
  },
  queryCity(parentId: string) {
    return post(
      env.VITE_API_ADMIN_CONTEXT_PATH + "/admin/api/code.city.query",
      {
        parentId,
      }
    );
  },
  /**
   *
   * @param parentId
   * @returns
   */
  async loadChilds(parentId: string): Promise<CodeTreeNode[]> {
    let treeData = Array<CodeTreeNode>();
    await apiCode
      .queryChildrenByParentId(parentId)
      .then((response: any) => {
        if (response.data.code == 200) {
          if (response.data.data != "") {
            treeData = utils.jsonArray2TypescriptArray(response.data.data);
          }
        }
      })
      .catch((err: any) => {
        utils.errorNotification("数据处理错误", err);
      });

    return treeData;
  },
};

export default apiCode;
